import urllib.request
import json, base64
import shutil,os


# 获取网页源码
def get_html(url):
    request = urllib.request.Request(url)
    request.add_header('user-agent', 'Mozilla/5.0')
    response = urllib.request.urlopen(request)
    html = response.read()
    string = html.decode("utf8")
    response.close()
    return string


# json数据转化字典方便使用
def json_loads(json_str):
    menu = ["VTM", "server", "server_port", "password", "method", "clock", "globe"]
    ss_list = []
    dict_temp = {}
    data = json.loads(json_str)
    for i,ss in enumerate(data["data"]):
        for j, k in enumerate(ss):
            if j == 2:
                dict_temp[menu[j]] = int(ss[j])
            else:
                dict_temp[menu[j]] = ss[j]
        ss_list.append(dict_temp)
        dict_temp = {}
    return ss_list

# 字典转换为SSR客户端gui_config格式字典
# {'VTM': '10/10/10', 'server': '62.113.255.12', 'server_port': 40010, 'password': 'vpnnest!@#123d', 'method': 'aes-256-cfb', 'clock': '16:17:07', 'globe': 'DE'}
def dict_json(dic={'VTM': '10/10/10', 'server': '62.113.255.12', 'server_port': 40010, 'password': 'vpnnest!@#123d', 'method': 'aes-256-cfb', 'clock': '16:17:07', 'globe': 'DE'}):
    gui_config_default = {
        "remarks" : "",
        "id" : "",
        "server" : "127.0.0.1",
        "server_port" : 2333,
        "server_udp_port" : 0,
        "password" : "wilson",
        "method" : "chacha20",
        "protocol" : "origin",
        "protocolparam" : "",
        "obfs" : "plain",
        "obfsparam" : "",
        "remarks_base64" : "",
        "group" : "wilson",
        "enable" : True,
        "udp_over_tcp" : False
    }
    remarks = dic["clock"]+"-"+dic["globe"]+"-"+dic["VTM"]
    gui_config_default["remarks"] = remarks
    gui_config_default["remarks_base64"] = base64.urlsafe_b64encode(remarks.encode('utf-8')).decode()[:-1]
    gui_config_default["server"] = dic["server"]
    gui_config_default["server_port"] = dic["server_port"]
    gui_config_default["password"] = dic["password"]
    gui_config_default["method"] = dic["method"]
    return gui_config_default


# 转换SSR配置文件,并返回dict
def json_dict(FilePath = "./tkinter-gui-config.json"):
    shutil.copy(FilePath, FilePath+".bak")
    gui_config_dict = {}
    with open(FilePath, mode="r", encoding = "utf-8") as f:
        gui_config_dict = json.loads(f.read())
    return gui_config_dict


def main():
    print("run...")
    url = "https://free-ss.site/ss.json"
    FilePath = "./tkinter-gui-config.json"
    gui_config_dict = json_dict()
    ss_list = json_loads(get_html(url))
    for i, dic in enumerate(ss_list):
        gui_config_dict["configs"].append(dict_json(dic=dic))
        print("第{}个..".format(i+1))
    with open(FilePath, mode="w", encoding="utf-8") as f:
        f.write(json.dumps(gui_config_dict, indent=4))
    print("ok")


if __name__ == '__main__':
    main()
    pass